package logic

import (
	"context"
	"errors"
	"fmt"
	"house-info-net/houserpc/houserpc"
	"house-info-net/houserpc/internal/svc"
	"house-info-net/models/cache"
	"house-info-net/models/mysql"
	"house-info-net/pkg"
	"math/rand"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 用户登录
func (l *UserLoginLogic) UserLogin(in *houserpc.UserLoginRequest) (*houserpc.UserLoginResponse, error) {
	// todo: add yourlogic here and delete this line

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
	if result != in.SmsCode {
		return nil, errors.New("短信验证码错误,请重新输入")
	}

	result2, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Mobile).Result()
	if result2 != in.Captcha {
		return nil, errors.New("图形验证码错误,请重新输入")
	}

	user := mysql.User{
		Mobile:    in.Mobile,
		Password:  in.Password,
		HeadImage: "https://c-ssl.dtstatic.com/uploads/blog/202303/30/20230330144441_9addb.thumb.400_0.jpg",
		NickName:  fmt.Sprintf("用户_%d", rand.Intn(1000)),
	}
	if err := user.UserFirstOrCreate(mysql.DB, in.Mobile); err != nil {
		return nil, errors.New("注册失败")
	}

	if pkg.Md5(in.Password) != user.Password {
		return nil, errors.New("密码错误,登录失败")
	}

	cache.Rdb.Del(l.ctx, "sendSms"+in.Mobile)
	cache.Rdb.Del(l.ctx, "captcha"+in.Mobile)
	
	return &houserpc.UserLoginResponse{
		UserId: int64(user.ID),
	}, nil
}
